/**
 * Created by zhaoxk on 2016/10/27.
 */
import React from 'react';
import {Form} from 'antd';
import _ from 'lodash';
import moment from 'moment';
import OW from './reportWidgets';
class _ReportForm extends React.Component {
    constructor(props) {
        super(props);
        const _type = this.props.normalize(this.props.types, 'cat');
        this.state = {
            forms: this.props.forms,
            types: _type,
            iHeight: this.props.iHeight || 'auto',
            items: this.props.items || [],
            cur: this.props.cur || 0
        };
    }

    componentWillMount() {
        this.props.form.setFieldsValue({
            forms: this.state.forms
        });
    }

    componentDidMount() {
        //禁止input记忆用户曾经输入的内容
        _.forEach(document.getElementsByTagName('input'), (input) => {
            if (input.getAttribute('type') === 'text') {
                input.setAttribute("AutoComplete", "off");
            }
        });
    }

    componentWillReceiveProps(prop) {
        const _this = this;
        if (prop.need2save) {
            _this.save((data) => {
                _this.props.receiveData(data);
            });
        } else {
            _this.setState({
                forms: prop.forms,
                iHeight: prop.iHeight || 'auto',
                items: prop.items || [],
                cur: prop.cur || 0,
                need2save: prop.need2save || false
            });
        }
    }

    save(cb) {
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (errors) {
                cb({
                    type: 'error',
                    value: errors
                });
                return;
            }
            //表单通过验证，开始序列化需要提交的数据
            const _items = {},
                items = [],
                makeObj = (obj, key) => {
                    if (!_.hasIn(obj, key)) {
                        obj[key] = {};
                    }
                    return obj[key];
                },
                normalized = (obj, tid, nid, index, value) => {
                    if (value instanceof moment) value = value.format('YYYY-MM-DD');
                    makeObj(makeObj(obj, tid), index)[nid] = value;
                };
            _.forIn(values, (v, k) => {
                const info = k.split('_'),
                    typeId = info[0],
                    nameId = info[1],
                    indexId = info[2];
                normalized(_items, typeId, nameId, indexId, v);
            });
            _.forIn(_items, (v, k) => {
                const typeData = {
                    type: k,
                    data: []
                };
                _.forIn(v, (v) => {
                    let hasData = false;
                    //遍历这组表单值，如果全部都为undefined，则不提交
                    _.forIn(v, (v) => {
                        if (typeof v !== 'undefined') {
                            hasData = true;
                            return false;
                        }
                    });
                    if (hasData) {
                        typeData.data.push(v);
                    } else {
                        return false;
                    }
                });
                _.forIn(k);
                items.push(typeData);
            });
            cb({
                type: 'willSubmit',
                value: items
            });
        });
    }

    changeCate(id, index) {
        if (index !== this.state.cur) {
            this.setState({
                cur: index
            }, () => {
                if (typeof this.props.changeCate === 'function') {
                    this.props.changeCate(id, index);
                }
            });
        }
    }

    toolEvent(type, typeId, i) {
        if (typeof this.props.toolEvent === 'function') {
            this.props.toolEvent(type, typeId, i);
        }
        /*if (typeof this.props[type] === 'function') {
            this.props[type](typeId, i);
        } else {
            console.error(type, 'toolBar事件未定义');
        }*/
    }

    updateValue(obj) {
        if (typeof this.props.updateValue === 'function') {
            this.props.updateValue(obj);
        }
    }

    renderForm(cate) {
        const forms = this.state.forms,
            _form_ = this.props.form,
            types = this.state.types,
            curT = types[cate];
        let results = [];
        if (curT) {
            for (let __i = 0; __i < curT.length; __i++) {
                let hasItem = false;
                const typeId = curT[__i].id,
                    typeLabel = curT[__i].label,
                    _form = forms[typeId];
                if (_form) {
                    for (let _i = 0; _i < _form.length; _i++) {
                        if (_form[_i]) {
                            hasItem = true;
                            break;
                        }
                    }
                }
                if (_form && hasItem) {                 //有数据，但是可能经过删除全是null
                    if (curT[__i].renderData) {         //有控件设置
                        results.push(
                            <div
                                className="typeBox"
                                key={typeId}
                            >
                                <h3>{typeLabel}</h3>
                                {_form.map((_f, _i) =>
                                    (_f ? (
                                        <OW
                                            key={`${typeId}${_i}`}
                                            _form_={_form_}
                                            tid={typeId}
                                            i={_i}
                                            initial={_f}
                                            formConfig={curT[__i].renderData}
                                            toolEvent={this.toolEvent.bind(this)}
                                            updateValue={this.updateValue.bind(this)}
                                        />
                                    ) : _f)
                                )}
                            </div>
                        );
                    } else {
                        results.push(
                            <div
                                key={`${typeId}_noneComp`}
                                className="nonComp"
                            >
                                {typeLabel} 控件还没有准备好
                            </div>
                        );
                    }
                } else {
                    results.push(
                        <div
                            key={`${typeId}_noneData`}
                            className="nonComp"
                        >
                            暂时没有 {typeLabel} 病历数据，您可以点击右侧的模板控件撰写病历
                        </div>
                    );
                }
            }
        } else {
            results = <div className="nonComp">该分类暂时不开放病历控件，敬请期待...</div>;
        }
        return results;
    }

    renderItems(items) {
        if (items.length > 0) {
            const cur = this.state.cur,
                _h = this.state.iHeight,
                _items = items.map((item, i) => (
                    <li
                        key={`report-${item.id}`}
                        id={`report-${item.id}`}
                        className={(i === cur) ? 'reportItem on' : 'reportItem'}
                        style={{
                            height: _h
                        }}
                    >
                        <div className="reportItemCont">
                            {this.renderForm(item.id, i)}
                        </div>
                    </li>
                )),
                top = (cur * (-1) * parseInt(_h)) + 'px';
            return (
                <Form
                    vertical
                >
                    <ul
                        id="_cateWrap"
                        style={{
                            top
                        }}
                    >
                        {_items}
                    </ul>
                </Form>
            );
        }
    }

    render() {
        return this.renderItems(this.state.items);
    }
}
const ReportForm = Form.create()(_ReportForm);
export default ReportForm;
